package com.study.kafka;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @author
 * @date 2022年08月26日 11:19
 * @description 事务示例
 */
public class CustomProducerTranction {

    public static void main(String[] args) {

        // 配置
        Properties properties = new Properties();

        // 连接kafka
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.160:9092");

        // 指定对应的key和value 的序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "010101");

        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);


        kafkaProducer.initTransactions();

        kafkaProducer.beginTransaction();

        try {

            // 发送数据
            for (int i = 0; i < 5; i++) {
                kafkaProducer.send(new ProducerRecord<>("first", "study" + i));
            }

            // 模拟不成功情况
            int i = 1 / 0;
            kafkaProducer.commitTransaction();
        } catch (Exception e) {
            kafkaProducer.abortTransaction();
        }finally {

            kafkaProducer.close();
        }


    }
}
